﻿using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.DomainFramework.BusinessService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Fuse8.ContentManagementFramework.Administration.Controllers
{
    public class CmsMediaPickerController : CmsAdminController
    {
        private CmsMediaService _mediaService = new CmsMediaService();
        private CmsMediaContentService _mediaContentService = new CmsMediaContentService();
        private const int _pageSize = 5;

        [HttpPost]
        public ActionResult Index(string elementId, string mediaTypes = null)
        {
            var mediaFolders = TransformToTree(_mediaService.FindAllWithSubfolders());

            var mediaContent = GetMediaContent(mediaTypes: mediaTypes);

            ViewBag.ElementId = elementId;
            ViewBag.MediaTypes = mediaTypes;

            return PartialView("Index", new Tuple<IEnumerable<CmsMedia>, IEnumerable<CmsMediaContent>>(mediaFolders, mediaContent));
        }

        public ActionResult Load(int mediaId = 0, string keyword = null, int page = 1, int size = _pageSize, string mediaTypes = null)
        {
            var result = GetMediaContent(mediaId, keyword, page, size, mediaTypes);

            return PartialView("Load", result);
        }

        public ActionResult Browse(string elementId)
        {
            var mediaFolders = _mediaService.FindAllWithSubfolders().OrderBy(c => c.ParentMediaId);

            ViewBag.ElementId = elementId;

            return PartialView("Browse", mediaFolders);
        }

        [HttpPost]
        public ActionResult SaveMediaContent(int mediaId, int fileId, string title)
        {
            if (mediaId > 0 && fileId > 0)
            {
                var file = new CmsMediaFileService().FindOne(fileId);
                if (file != null)
                {
                    var mediaContentName = !string.IsNullOrEmpty(title) ? title : file.OriginalFileName;

                    var mediaContent = new CmsMediaContent
                    {
                        MediaId = mediaId,
                        MetaCode = mediaContentName,
                        MediaContentName = mediaContentName
                    };

                    _mediaContentService.Add(mediaContent);

                    var mediaContentFileLink = new CmsMediaContentFileLink
                    {
                        MediaContentId = mediaContent.Id,
                        MediaFileId = fileId,
                        IsPrimary = true
                    };
                    new BusinessServiceFacade<CmsMediaContentFileLink, int>().Add(mediaContentFileLink);

                    return Json(new { IsMediaSaved = true, MediaContentId = fileId, LinkedFile = file.LinkedFileName });
                }
            }

            return Json(new { IsMediaSaved = true });
        }

        private List<CmsMediaContent> GetMediaContent(int mediaId = 0, string keyword = null, int page = 1, int size = _pageSize, string mediaTypes = null)
        {
            var mediaContent = _mediaContentService.FindAll();

            if (mediaId > 0)
            {
                mediaContent = mediaContent.Where(c => c.MediaId == mediaId);
            }

            if (!string.IsNullOrWhiteSpace(keyword))
            {
                keyword = keyword.Trim();
                mediaContent = mediaContent.Where(c => c.MediaContentName.Contains(keyword));
            }

            if (!string.IsNullOrWhiteSpace(mediaTypes))
            {
                var mt = mediaTypes.Split(',');
                mediaContent = (from s in mt from cmsMediaContent in mediaContent where cmsMediaContent.MainFile.ContentType == s select cmsMediaContent).ToList();
            }
            var result = mediaContent.OrderBy(c => c.MediaContentName).Take(size * page).Skip(size * (page - 1)).ToList();

            ViewBag.TotalItems = mediaContent.Count();
            ViewBag.FolderId = mediaId;
            ViewBag.Keyword = keyword;
            ViewBag.MediaTypes = mediaTypes;

            return result;
        }

        private IEnumerable<CmsMedia> TransformToTree(IEnumerable<CmsMedia> mediaItems)
        {
            var result = mediaItems.OrderBy(x => x.ParentMediaId).ToList();
            var count = result.Count();
            for (int i = count - 1; i >= 0; i--)
            {
                var element = result[i];
                var parent = result.FirstOrDefault(x => x.Id == element.ParentMediaId);
                if (parent == null) continue;
                if (parent.SubFolders == null)
                {
                    parent.SubFolders = new List<CmsMedia>();
                }
                var temp = parent.SubFolders.ToList();
                temp.Add(element);
                parent.SubFolders = temp;
                result.Remove(element);
            }
            return result;
        }
    }
}